package ru.rchervot.sanasar.server;

import ru.rchervot.sanasar.client.model.ItemObjectCandidate;
import ru.rchervot.sanasar.client.model.Query;
import ru.rchervot.sanasar.client.model.ResultsPage;
import ru.rchervot.sanasar.client.model.SearchResultsItemCandidates;
import ru.rchervot.sanasar.client.rpc.GetItem;
import ru.rchervot.sanasar.client.rpc.GetItemResponse;
import ru.rchervot.sanasar.client.rpc.GetPage;
import ru.rchervot.sanasar.client.rpc.GetPageResponse;
import ru.rchervot.sanasar.client.rpc.GetQuery;
import ru.rchervot.sanasar.client.rpc.GetQueryResponse;
import ru.rchervot.sanasar.client.rpc.RPCService;
import ru.rchervot.sanasar.client.rpc.SaveQuery;
import ru.rchervot.sanasar.client.rpc.SaveQueryResponse;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

public class RPCServiceServer extends RemoteServiceServlet implements RPCService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;



	@Override
	public SaveQueryResponse execute(SaveQuery action) throws Exception {
		try {
			SearchServiceServerCandidate ssc = new SearchServiceServerCandidate();

			Integer queryId = ssc.saveQueryToDB(action.getQuery());
			
			action.getQuery().setID(queryId);
			
			ssc.processQuery(action.getQuery());
			
			return new SaveQueryResponse(queryId);
			
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception(ex);
		}
	}
	
	@Override
	public GetPageResponse<SearchResultsItemCandidates> 
	execute(GetPage action) throws Exception {
		try {
			SearchServiceServerCandidate ssc = new SearchServiceServerCandidate();
			ResultsPage<SearchResultsItemCandidates> rp = 
				ssc.getPage(action.getQueryId(), action.getOffset(), action.getPageSize());
			
			return new GetPageResponse<SearchResultsItemCandidates>(rp);
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception(ex);
		}
	}
	
	public GetItemResponse<ItemObjectCandidate> execute(GetItem action) throws Exception {
		try {
			SearchServiceServerCandidate ssc = new SearchServiceServerCandidate();

			ItemObjectCandidate item = ssc.loadItemView(action.getQueryId(), action.getOffset());
			
			return new GetItemResponse<ItemObjectCandidate>(item);
			
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception(ex);
		}
	}
	
	public GetQueryResponse execute(GetQuery action) throws Exception {
		try {
			SearchServiceServerCandidate ssc = new SearchServiceServerCandidate();

			Query query = ssc.loadQuery(action.getQueryId());
			
			return new GetQueryResponse(query);
			
		} catch (Exception ex) {
			ex.printStackTrace();
			throw new Exception(ex);
		}
	}
}
